package com.ruoyi.erecord.samplebox.service.impl;

import org.springframework.stereotype.Service;

import com.ruoyi.common.tools.constant.ERecordConstant;
import com.ruoyi.common.tools.excel.MyExcelUtil;
import com.ruoyi.common.tools.excel.base.MyExcelResult;
import com.ruoyi.common.tools.excel.listener.SampleboxExcelListener;
import com.ruoyi.common.tools.utils.SerialGenerator;
import com.ruoyi.erecord.samplebox.domain.bo.SampleboxImportBaseBo;
import com.ruoyi.erecord.samplebox.domain.vo.SampleboxImportDetailVo;
import com.ruoyi.erecord.samplebox.service.ISampleboxImportBaseService;
import com.ruoyi.erecord.samplebox.service.ISampleboxImportDetailService;
import com.ruoyi.erecord.samplebox.service.ISampleboxService;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Service
public class SampleboxImportService {
	private final ISampleboxService sampleboxService;
	private final ISampleboxImportBaseService sampleboxImportBaseService;
	private final ISampleboxImportDetailService sampleboxImportDetailService;

	/**
	 * 导入人员excel数据
	 * 
	 * @param bo
	 * @return
	 */
	public Boolean importExcel(SampleboxImportBaseBo bo) {
		// 生成批次号
		final String batchNo = SerialGenerator.generator.nextId();
		bo.setBatchNo(batchNo);

		// excel 处理
		MyExcelResult<SampleboxImportDetailVo> excelResult = MyExcelUtil.getImportExcelData(batchNo,
				bo.getExcelUrl(), new SampleboxExcelListener(batchNo), SampleboxImportDetailVo.class);

		if (null == excelResult) {
			return false;
		}

		// 更新主表状态
		if (excelResult.isSuccess()) {
			bo.setProcessStatus(ERecordConstant.COMMON_STATUS_SUCCESS);
		} else {
			bo.setProcessStatus(ERecordConstant.COMMON_STATUS_ERROR);
		}
		bo.setProcessMsg(excelResult.getAnalysis());
		//bo.setAttachMsg(ERecordConstant.ATTACH_UPLOAD_STATUS_NO);
		// 入库主表
		if (this.sampleboxImportBaseService.insertByBo(bo)) {
			// 入库子表
			if (!excelResult.getList().isEmpty()) {
				if (!this.sampleboxImportDetailService.batchInsertBo(excelResult.getList())) {
					return false;
				}
			}
		} else {
			return false;
		}

		if (excelResult.isSuccess() && !excelResult.getList().isEmpty()) {
			// 更新车辆表
			this.sampleboxService.batchInsertOrUpdate(batchNo);
		}

		return true;
	}
}
